<?php

namespace App\Http\Controllers\Setting;

use App\Http\Controllers\Controller;
use App\Libraries\Common;
use Illuminate\Http\Request;
use DB, Breadcrumbs, Toastr;
use App\Repositories\PermissionRepositoryEloquent;

class PermissionController extends Controller
{
    // 正则表达式
    public $regex = ['/class\s(.+?)Controller\sextends/i', '/public function\s(.+?)\(.+?\{(.+?)\}/', '/data\[\'title\'\]\s*=\s*\'(.+?)\'/'];
    // 过滤目录及文件
    public $filter = ['Auth', 'Controller.php'];

    protected $permission;

    public function __construct(PermissionRepositoryEloquent $permission)
    {
        $this->permission = $permission;
    }

    public function index(Request $request)
    {
        $data['title'] = '权限列表';
        $data['menu'] = $this->permission->getTopPermission();
        return view('setting.permission.index', $data);
    }

    public function save(Request $request)
    {
        $data['title'] = '权限保存';
        foreach ($request->input('name') as $k => $val)
        {
            $data = [
                'name' => str_replace('|-- ', '', $request->input('name')[$k]),
                'status' => isset($request->input('status')[$k]) ? 1 : 0,
                'sort' => $request->input('sort')[$k],
                'icon' => $request->input('icon')[$k]
            ];
            DB::table('permissions')->where('id', $k)->update($data);
        }
        return redirect('/msg')->with(['msg' => '保存成功']);
    }

    public function store(CreateRequest $request)
    {
        Toastr::error('新权限添加失败!');
    }

    public function show($id)
    {
    }

    public function destroy($id)
    {
        $result = $this->permission->delete($id);
        return response()->json(['ack' => $result]);
    }

    public function destroyAll(Request $request)
    {
        if(!($ids = $request->get('ids', []))) {
            return response()->json(['ack' => 0, 'msg' => '请求参数错误']);
        }
        foreach ($ids as $id) $this->permission->delete($id);
        return response()->json(['ack' => 1]);
    }

    public function refresh()
    {
        $data['title'] = '刷新权限';
        $path = app_path('Http/Controllers');
        $files_map = Common::directory_map($path);
        foreach ($files_map as $dir => $fm)
        {
            // 过滤跳过的目录及文件
            if (in_array($dir, $this->filter) || in_array($fm, $this->filter)) continue;
            // php7+三元运算符, 兼容含命名空间的目录结构
            $namespace = '';
            if (!is_numeric($dir))
            {
                $namespace = $dir;
                $nca[] = ['namespace' => strtolower($namespace)];
            }
            foreach (is_array($fm)?$fm:[$fm] as $f)
            {
                $filepath = $namespace ? $path.DIRECTORY_SEPARATOR.$namespace.DIRECTORY_SEPARATOR.$f : $path.DIRECTORY_SEPARATOR.$f;
                $file_content = php_strip_whitespace($filepath);
                preg_match_all($this->regex[0], $file_content, $class);
                if(isset($class[1][0]))
                {
                    $controller = trim(strtolower($class[1][0]));
                    preg_match_all($this->regex[1], $file_content, $function);
                    if(isset($function[1]))
                    {
                        foreach ($function[1] as $key => $action)
                        {
                            $action = trim(strtolower($action));
                            if ($action == '__construct') continue;
                            preg_match_all($this->regex[2], $function[2][$key], $title);
                            $desc = empty($title[1]) ? '' : trim($title[1][0]);
                            $nca[] = [
                                'namespace' => strtolower($namespace),
                                'controller' => $controller,
                                'action' => $action,
                                'name' => $desc,
                            ];
                        }
                    }
                }
            }
        }
        foreach ($nca as $n)
        {
            try
            {
                DB::table('permissions')->insert($n);
            }
            catch (\Illuminate\Database\QueryException $e)
            {
                continue;
            }
        }
        return redirect('/msg')->with(['msg' => '成功刷新']);
    }
}
